<?php
class LetterController extends MyClass_Action {
	protected $controller;
	protected $action;
	protected $_user;
	protected $arrs;
	public function init() {
		$this->commonAction();	
	}
	

/*
获取所有家长登陆帐号并群发私信
*/
	 public function autouserAction() {
		try { 
		    //$yunyingDb=$this->getDbLink(1);
			//取所有班级uid
			$sql="select uid,class_uid,cnname,schoolname,classname from student_class_v  where groupid=1 and city='北京'";
			$student=$this->_dbAdapter->fetchAll($sql);

			$class=array();
			$uidlist=array();
			foreach($student as $key => $value){
				$class[$value['class_uid']][$value['uid']]=$value;
				if(!in_array($value['uid'],$uidlist))
					$uidlist[]=$value['uid'];
			}
			//print_r($class);exit;
			$sql='select uid,username,password from student_parents_v where uid in ('.implode(',',$uidlist).')';			
			$parentslist = $this->_dbAdapter->fetchAssoc($sql); 
			
			foreach($class as $key => $value){
				foreach($value as $key1 => $value1){
					if(isset($parentslist[$key1]['username'])){
						$class[$key][$key1]['username']=$parentslist[$key1]['username'];
						$class[$key][$key1]['password']=$this->authcode($parentslist[$key1]['password'], 'DECODE', 'mactop') ;									
					}
				}
			}
					
			//发私信 && csv
			foreach($class as $key=>$value){
				$csv_user="学校,班级,姓名,帐号,密码\r\n";
				$content='';
				foreach($value as $key1 => $value1){
					if($value1['username']){
						$content .=$value1['cnname'].' 帐号:'.$value1['username'].' 密码:'.$value1['password']."\r\n";
						$csv_user .=$value1['schoolname'].','.$value1['classname'].','.$value1['cnname'].','.$value1['username'].','.$value1['password']."\r\n";
					}
				}
				$data=array(
				 	'letter_type'=>'txt',
				 	'from_role'=>'admin',
				 	'from_uid'=>$this->_user->id,
				 	'to_role'=>'teacher',
				 	'to_uid'=>$key,
				 	'content'=>$content,
				 	'addtime'=>time(),
				 );
			//	$presult=$this->_dbAdapter->insert('letter',$data); 
				
				
				//$str = iconv("utf-8", "gbk",$value1['classname']);
				//$str1 = iconv("utf-8", "gbk",$value1['schoolname']);
				//file_put_contents(PROJECT_ROOT . '/public/csv/'.$str1.'--'.$str.'.csv', $csv_user);
				
				$csv_user=mb_convert_encoding($csv_user, "GBK", "UTF-8");	
				file_put_contents(PROJECT_ROOT . '/public/csv/'.$value1['schoolname'].'--'.$value1['classname'].'.csv', $csv_user);	
			}
			
			//$this->zip(PROJECT_ROOT . '/public/csv/',PROJECT_ROOT.'/public/csvall.zip');
			exit;

		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning',3 );
		}
	}
/*
群发私信
*/
	 public function autoletterAction() {
		try { 	
			//$content2 = $this->_request->getParam ('word');
			//if(empty($content2)){
				//throw new Exception ('请输入私信内容');
			//}		
		    //$yunyingDb=$this->getDbLink(1);
			//取所有班级uid
			$sql="select uid,class_uid,cnname,schoolname,classname from student_class_v  where groupid=1 and city='北京' and schoolid<>29";
			$student=$this->_dbAdapter->fetchAll($sql);

			$class=array();
			$uidlist=array();
			foreach($student as $key => $value){
				$class[$value['class_uid']][$value['uid']]=$value;
				if(!in_array($value['uid'],$uidlist))
					$uidlist[]=$value['uid'];
			}
			
			//发私信 && csv
			foreach($class as $key=>$value){
				//群发私信
/*				$content2='新版本升级通知（重要）' . "\r\n" . '各位老师您好：' . "\r\n" . '
根据反馈信息发现，个别教师端在网络可用的情况下（可登陆QQ、微信等）存在上传列表积压。我们非常重视这个问题，并组织全部力量去调查、分析、解决，最终推出了V1.2.1版教师助手。经测试该版本已解决该问题，请老师尽快升级！' . "\r\n" . '
如何知道正在使用哪个版本：可按（云中校车---->设置---->关于我们）的方式查看。' . "\r\n" . '
如何知道我的系统是否积压：可按（云中校车---->班级---->上传列表）的方式查看。' . "\r\n" . '
更新后请彻底退出云中校车教师助手，并重新登录或者直接重启itouch。' . "\r\n" . '
在网络可用的情况下（可登陆QQ、微信等）不要锁屏，积压的照片即可上传。' . "\r\n" . '
如网络不可用造成的积压，请及时联系伊顿IT部，我们也会尽最大努力配合园区与IT部沟通解决。' . "\r\n" . '
升级方法：打开itouch里的App Store，点击最下方更新按钮，找到教师助手进行更新即可。' . "\r\n" . '
公用Apple ID:app@mac-top.mobi，密码:Mactop2013；也可以使用自己的苹果账号。' . "\r\n";				
*/				

				//$content2='班级学生信息不对怎么办？' . "\r\n" . '(1) 较少学生信息错误时---老师您可把需要修改的学生姓名使用云中校车系统消息发过来，我们收到后会马上处理。' . "\r\n" . '(2) 较多学生信息错误时---老师您可以把学生名单拍张照片传给我们或者将电子档学生名单放到您电脑的共享文件夹里，我们收到后会马上处理。' . "\r\n" . '(3)如果全新的学生加入班级时（即未在本校园学习过）---老师您可以拍摄一张新生报名报的照片，使用云中校车系统消息发过来，并说明是新生入园。我们收到后会马上给您处理。' . "\r\n" ;
				
			/*	$content2="教师助手V1.2.0升级通知" . "\r\n" . "
各位老师，根据大家的建议与意见，新版本改进了以下功能，请老师尽快升级！" . "\r\n" . "
1、  优化了上传功能，解决照片上传失败问题；" . "\r\n" . "
2、  可以拍摄微视频；" . "\r\n" . "
3、  可以读取从电脑导入的相册；" . "\r\n" . "
4、  可以为照片添加分类；" . "\r\n" . "
5、  可查看已发布通知和家长回执的情况；" . "\r\n" . "
6、  可以查看班级的学生列表；" . "\r\n" . "
7、  修正了发通知时截取图片等功能。" . "\r\n" . "
升级方法：打开App Store应用，点击右下方更新按钮，找到教师助手，点击更新即可。" . "\r\n" . "
如需登录名及密码，可以使用自己的苹果账号。" . "\r\n" . "
或公用Apple ID:app@mac-top.mobi，密码:Mactop2013" . "\r\n";
 
$content2="The new version update notification" . "\r\n" . "
Dear teachers, according to the suggestions and comments, the new version improve the following features." . "\r\n" . "
1, optimize the upload function, to solve the problem of upload failure;" . "\r\n" . "
2,Short video;" . "\r\n" . "
3,upload the albums whichare imported from your computer;" . "\r\n" . "
4, photos can be categorized;" . "\r\n" . "
5, view the published notices, and who has confirmed it;" . "\r\n" . "
6, view the class student list;" . "\r\n" . "
7,optimize some featuresand fix bugs." . "\r\n" . "
Update method: Open the iPod's App Store, click on the Update button at the bottom, you can find TeacherPal update tip." . "\r\n" . "
Public Apple ID: app@mac-top.mobi, password:Mactop2013; You can use your own Apple ID." . "\r\n";*/

				$data=array(
				 	'letter_type'=>'txt',
				 	'from_role'=>'admin',
				 	'from_uid'=>$this->_user->id,
				 	'to_role'=>'teacher',
				 	'to_uid'=>$key,
				 	'content'=>$content2,
				 	'addtime'=>time(),
				 );
				$presult=$this->_dbAdapter->insert('letter',$data); 
				
				
							
			}
			exit;

		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning',3 );
		}
	}
//自动发私信，统计照片情况
	 public function autoAction() {
		try { 
			 //每周一八点发私信
			 if(date('w')<>'1' || date('G')<'8'){
				 exit;
			 }
			 
			 $sql='select value from setting where variable="letter_teacher_push"';
			 $letter_teacher_push=$this->_dbAdapter->fetchOne($sql);
			 
			 if($letter_teacher_push <> date('Y-m-d')){
				$res=$this->_dbAdapter->update('setting',array('value'=>date('Y-m-d')),'variable="letter_teacher_push"'); 
				if($res){
					$this->autostatic();
					//$this->autostaticvideo();
				}
			 }
			 exit;
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning',3 );
		}
	 }
	 //统计照片情况
	 public function autostatic() {
		try {
		
		    //$yunyingDb=$this->getDbLink(1);
			
			//取所有学生uid
			$sql="select studentid,class_uid,cnname,schoolname,classname from student_class_v where groupid=1 and city='北京'";
			$student=$this->_dbAdapter->fetchAll($sql);
			$class=array();
			foreach($student as $key => $value){
				$value['imgnum']=array(0,0);
				$value['videonum']=array(0,0);
				$class[$value['class_uid']][$value['studentid']]=$value;
			}

			//获取时间段的所有文章
			$start_date=date('Y-m-d',strtotime("-7 day"));
			$end_date=date('Y-m-d');
			//$start_date="2014-03-17";
			//$end_date="2014-03-31";
			
			$sql='SELECT articlefilesid,articlekey,uid_class,memberlist,from_unixtime(uploadtime,"%Y-%m-%d") as uploadtime,fext FROM `article_files` where groupid=1 and isdelete=0 and ischecked=1   and articlekey<>""';
			//echo $sql;   and fext<>"mp4"
			$articleidlist=$this->_dbAdapter->fetchAll($sql);
			//print_r($articleidlist);echo '<br />';
			if($articleidlist)
				foreach($articleidlist as $key=>$value){
					$memberlist=explode(',',$value['memberlist']);
					if($value['fext']<>'mp4'){
						if(is_array($memberlist)){
							foreach($memberlist as $key1=> $value1){
								if(!isset($class[$value['uid_class']][$value1]))
									continue;
								$class[$value['uid_class']][$value1]['imgnum'][1]++;	
								if($value['uploadtime']>=$start_date && $value['uploadtime']<=$end_date)
									$class[$value['uid_class']][$value1]['imgnum'][0]++;	
							}
						}else{
							if(!isset($class[$value['uid_class']][$memberlist]))
								continue;
							$class[$value['uid_class']][$memberlist]['imgnum'][1]++;	
							if($value['uploadtime']>=$start_date && $value['uploadtime']<=$end_date)
								$class[$value['uid_class']][$memberlist]['imgnum'][0]++;	
						}
					}else{
						if(is_array($memberlist)){
							foreach($memberlist as $key1=> $value1){
								if(!isset($class[$value['uid_class']][$value1]))
									continue;
								$class[$value['uid_class']][$value1]['videonum'][1]++;	
								if($value['uploadtime']>=$start_date && $value['uploadtime']<=$end_date)
									$class[$value['uid_class']][$value1]['videonum'][0]++;	
							}
						}else{
							if(!isset($class[$value['uid_class']][$memberlist]))
								continue;
							$class[$value['uid_class']][$memberlist]['videonum'][1]++;	
							if($value['uploadtime']>=$start_date && $value['uploadtime']<=$end_date)
								$class[$value['uid_class']][$memberlist]['videonum'][0]++;	
						}
					}
					
				}
			
			//print_r($class);echo '<br />';exit;
			//发私信 && csv
			foreach($class as $key=>$value){
				//$csv_photo="姓名,上周照片数,类计照片数\r\n";
				$content1='自'.$start_date.'至'.$end_date.date(' H:i').' 本班学生拍摄照片及视频统计:'."\r\n".'姓名    上周照片    照片累计    上周视频    视频累计'."\r\n";
				foreach($value as $key1 => $value1){
					if($value1['cnname'])
						$content1 .=$value1['cnname'].'    '.$value1['imgnum'][0].'    '.$value1['imgnum'][1].'    '.$value1['videonum'][0].'    '.$value1['videonum'][1]."\r\n";
					//$csv_photo .=$value1['cnname'].','.$imgnum.','.$imgnum_all."\r\n";
				}
				//$str = iconv("utf-8", "gbk",$value1['classname']);
				//$str1 = iconv("utf-8", "gbk",$value1['schoolname']);
				//$str=mb_convert_encoding($value1['classname'], "GB2312", "UTF-8");
				//$str1=mb_convert_encoding($value1['schoolname'],  "GB2312","UTF-8");
				//echo mb_detect_encoding($value1['schoolname']);exit;
				//file_put_contents(PROJECT_ROOT . '/public/'.$str1.'--'.$str.'.csv', $csv_photo);	

				$data1=array(
				 	'letter_type'=>'txt',
				 	'from_role'=>'admin',
				 	'from_uid'=>3,
				 	'to_role'=>'teacher',
				 	'to_uid'=>$key,
				 	'content'=>$content1,
				 	'addtime'=>time(),
				 );
				//print_r($data1);echo '<br />';
				$presult1=$this->_dbAdapter->insert('letter', $data1); 	
			}
			exit;

		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning',3 );
		}
	}
	
	
/*	 //统计视频情况
	 public function autostaticvideo() {
		try { 
		
		    $yunyingDb=$this->getDbLink(1);
			
			//取所有学生uid
			$sql="select studentid,class_uid,cnname,schoolname,classname from student_class_v where city='北京'";
			$student=$yunyingDb->fetchAll($sql);
			$class=array();
			foreach($student as $key => $value){
				$value['imgnum']=array(0,0);
				$class[$value['class_uid']][$value['studentid']]=$value;
			}

			//获取时间段的所有视频文章
			$start_date=date('Y-m-d',strtotime("-7 day"));
			$end_date=date('Y-m-d');
			
			$sql='SELECT articlefilesid,articlekey,uid_class,memberlist,from_unixtime(uploadtime,"%Y-%m-%d") as uploadtime FROM `article_files` where isdelete=0 and ischecked=1 and fext="mp4"  and articlekey<>""';
			$articleidlist=$yunyingDb->fetchAll($sql);
			if($articleidlist)
				foreach($articleidlist as $key=>$value){
					$memberlist=explode(',',$value['memberlist']);
					if(is_array($memberlist)){
						foreach($memberlist as $key1=> $value1){
							if(!isset($class[$value['uid_class']][$value1]))
								continue;
							$class[$value['uid_class']][$value1]['imgnum'][1]++;	
							if($value['uploadtime']>=$start_date && $value['uploadtime']<=$end_date)
								$class[$value['uid_class']][$value1]['imgnum'][0]++;	
						}
					}else{
						if(!isset($class[$value['uid_class']][$memberlist]))
							continue;
						$class[$value['uid_class']][$memberlist]['imgnum'][1]++;	
						if($value['uploadtime']>=$start_date && $value['uploadtime']<=$end_date)
							$class[$value['uid_class']][$memberlist]['imgnum'][0]++;	
					}
				}
			
			//发私信 && csv
			foreach($class as $key=>$value){
				$content1='自'.$start_date.'至'.$end_date.date(' H:i').' 本班学生拍摄视频统计:'."\r\n".'姓名    上周    所有累计'."\r\n";
				foreach($value as $key1 => $value1){
					if($value1['cnname'])
						$content1 .=$value1['cnname'].'    '.$value1['imgnum'][0].'    '.$value1['imgnum'][1]."\r\n";
				}
				$data1=array(
				 	'letter_type'=>'txt',
				 	'from_role'=>'admin',
				 	'from_uid'=>3,
				 	'to_role'=>'teacher',
				 	'to_uid'=>$key,
				 	'content'=>$content1,
				 	'addtime'=>time(),
				 );
				$presult1=$this->_dbAdapter->insert('letter', $data1); 	
			}
			exit;

		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning',3 );
		}
	}
	
*/	




    //列表   
	public function indexAction(){
		try {
			//查找给运维发消息的班级uid，班级id是唯一的
            $sql = "select DISTINCT(from_uid) as tid,classid from letter where isdelete=0 and to_role='admin' and from_role='teacher'";	
			$cids = $this->_dbAdapter->fetchAll($sql);
			//print_r($cids);echo '<br />';
			//获得该班级的最后一条私信
			foreach($cids as $cid){
			    //如果运维是回复的最后一条，则该记录被忽略,只显示老师为最后一条的信息
				$sql = "select from_role as role from letter where (to_role='teacher' and to_uid=".$cid['tid'].") or(from_role='teacher' and from_uid='".$cid['tid']."') order by addtime desc limit 1";
				$one = $this->_dbAdapter->fetchOne($sql);
				if($one=='teacher'){
				    $sql = "select letterid,from_uid as tid,addtime,content,classid from letter where classid=".$cid['classid']." and from_uid=".$cid['tid']." order by addtime desc limit 1";
					$row = $this->_dbAdapter->fetchRow($sql);	
					$row['over']=0;
					$result[] = $row;
				}elseif($one=='admin'){
				    $sql = "select letterid,to_uid as tid, addtime,content,classid from letter where classid=".$cid['classid']." and to_uid=".$cid['tid']." and from_unixtime(addtime,'%Y-%m-%d')='".date('Y-m-d')."' order by addtime desc limit 1";
					//echo $sql;echo '<br />';
					$row = $this->_dbAdapter->fetchRow($sql);	
					//print_r($row);echo '<br />';
					if($row){
						$row['over']=1;
						$result[] = $row;
					}
				}	
			}
			//print_r($result);exit;
			$num=count($result);
			for($i=0;$i<$num-1;$i++){
				for($j=$i+1;$j<$num;$j++){
					if($result[$j]['addtime']>$result[$i]['addtime']){
						$t=$result[$j];
						$result[$j]=$result[$i];
						$result[$i]=$t;
					}
				}
			}
			//print_r($result);echo '<br />';exit;
			foreach($result as $k=>$rs){
				   $teacher[$k]['lid'] = $rs['letterid'];
				   $teacher[$k]['tid'] = $rs['tid'];
				   $teacher[$k]['classid'] = $rs['classid'];
				   $teacher[$k]['over']  = $rs['over'];
				   $teacher[$k]['addtime'] = MyClass_Common::getDateInfo($rs['addtime']);
				   //print_r($teacher[$k]['addtime']);exit;
				   $sql = "select groupid,groupname,schoolname,classname,teachername from teacher_class_duty_v where inactive=0 and classid=".$rs['classid']." and teacherid=".$rs['tid'];
				   $row = $this->_dbAdapter->fetchRow($sql);
				   $teacher[$k]['groupid']  = $row['groupid'];
				   $teacher[$k]['groupname']  = $row['groupname'];
				   $teacher[$k]['schoolname'] = $row['schoolname'];
				   $teacher[$k]['classname']  = $row['classname'];
				   $teacher[$k]['teachername']  = $row['teachername'];
				  // $teacher[$k]['duty']  = $row['duty'];
				   $teacher[$k]['content']    = mb_substr($rs['content'],0,15);
			}
			
			$num=count($teacher);
			for($i=0;$i<$num-1;$i++){
				for($j=$i+1;$j<$num;$j++){
					if($teacher[$j]['groupid']<$teacher[$i]['groupid']){
						$t=$teacher[$j];
						$teacher[$j]=$teacher[$i];
						$teacher[$i]=$t;
					}
				}
			}

			$this->view->teacher=$teacher; 
			//print_r($teacher);exit;
		}catch ( Exception $e ){
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	//历史记录
	public function historyAction(){
		try {
		   $result = $this->_dbAdapter->fetchAll("select groupid,groupname from groups");				
		   $this->view->result=$result; 
		   
		   $content = $this->_request->getParam ('content');
		   $groupid = $this->_request->getParam ('group_id');		   
		   $letterid = $this->_request->getParam ('letterid');		   
		   $this->view->content=$content; 		   
		   $this->view->group_id=$groupid; 
		   if( $groupid  ){	
		   	   
		   $sql="select a.letterid,a.from_role,a.from_uid,a.to_uid,a.content,a.addtime,a.letter_type,a.classid,b.classname,b.groupid,b.teachername from letter a left join teacher_class_duty_v b on a.classid=b.classid and (a.from_uid=b.teacherid or a.to_uid=b.teacherid) where b.inactive=0 and a.isdelete=0 and b.groupid=".$groupid." and a.content like '%".$content."%' order by addtime desc";
		   $seo_all=$this->_dbAdapter->fetchAll($sql);
		   //print_r($seo_all);exit;
		   if($letterid){
			   $sql="select * from letter where letterid=".$letterid;
			   $uid=$this->_dbAdapter->fetchRow($sql);
			   //print_r($uid);exit;
			   if($uid['from_role']=='admin'){
				   $tid=$uid['to_uid'];
			   }else{
			   	   $tid=$uid['from_uid']; 
			   }
			   //print_r($uid);exit;
			   $sql = "select letterid,from_role,from_uid,to_uid,content,addtime,letter_type,classid from letter where isdelete=0 and classid=".$uid['classid']." and (from_role='teacher' and from_uid=".$tid." or (to_role='teacher' and to_uid=".$tid.") ) order by addtime asc " ;
			   $seo_all = $this->_dbAdapter->fetchAll($sql);
			   //print_r($seo_all);echo '<br />';
		   }
		   foreach($seo_all as $key=>$value){
			   if($value['from_role']=='admin'){
				   $seo_all[$key]['tid']=$value['to_uid'];
			   }else{
			   	   $seo_all[$key]['tid']=$value['from_uid']; 
			   }
		   }
			foreach($seo_all as $k=>$ar){
			    $role[] =  $ar['from_role'];
				$data[$k]['role'] = $ar['from_role'];
				
				$r = $this->_dbAdapter->fetchRow("select groupname,schoolname,classname,teachername from teacher_class_duty_v where inactive=0 and classid=".$ar['classid']." and teacherid='".$ar['tid']."'");				
				$data[$k]['detail']  = $r['groupname'].">".$r['schoolname'].">".$r['teachername'];
				$data[$k]['uname']  = $r['teachername'];
				
		        if($ar['letter_type']=='img'){			   
					$sql = "select concat('http://',cloudhost,cloudpath,filename,'.',fext,'.small.jpg') as imgurl,concat('http://',cloudhost,cloudpath,filename,'.',fext) as bigurl from letter_files where letterid='".$ar['letterid']."'";
					$r = $this->_dbAdapter->fetchRow($sql);
					$data[$k]['content'] = "<a href='#bigImg".$ar['letterid']."' role='button' class='btn' data-toggle='modal'><img src='".$r['imgurl']."' alt='没有找到云上的图片'></a>
                                            <div id='bigImg".$ar['letterid']."' class='modal hide fade' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
  <div class='modal-header'>
    <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
    <h3 id='myModalLabel'>Modal header</h3>
  </div>
  <div class='modal-body'>
    <img src='".$r['bigurl']."' alt='没有找到云上的大图片'>
  </div>
</div>";
				}else{
					$data[$k]['content']=str_replace(' ','&nbsp;',str_replace("\r\n",'<br>',$ar['content']));
				}
				$data[$k]['addtime'] = MyClass_Common::getDateInfo($ar['addtime']);
				$data[$k]['letterid'] = $ar['letterid'];
				$data[$k]['tid'] = $ar['tid'];
				$data[$k]['classid'] = $ar['classid'];
		   }
		  //print_r($data);exit;
	  if($letterid){
		   foreach($data as $da){
			   if($da['role']=='teacher'){
		       	    $str .="<div class='from'>";
					$school=$da['detail'];	
					$class=$da['uname'];	
			   }else{
		       	    $str .="<div class='to'>";			  			   
			   }
			   $str .= $da['role']=="teacher"?$da['uname']."[":'运维[';	
               $str .= $da['addtime'];		   
			   $str .="]：</div>";
			   
			   if($da['role']=='teacher'){
					$str .="<p class='from1 alert alert-error'>";			  			   
			   }else{
					$str .="<p class='to1 alert alert-success'>";			  			   
			   }
			   
			   $str .="";
			   if(!$letterid){
				   $str .="<a href='/letter/history/group_id/".$groupid."/letterid/".$da['letterid']."/content/".$da['content']."'>".$da['content']."</a>";
			   }else{
				   $str .=$da['content'];
			   }
			   $str .="</a></p>";
		   }
		    //$start ="<div><a href='/letter/delete/cid/".$cid."'>删除记录</a></div><br />";	
			$detail .="<h3>正在与&nbsp;<span style='color:red;'>".$class."</span>&nbsp;的老师对话：</h3><h4 style='color:gray'>[".$school."]</h4>";
			$str =$detail. $str;	
		   //$str=!empty($str)?$start.$str:'';
		   $str=!empty($str)?$str:'';
		   $this->view->str=$str; //print_r($str);exit;
		   $this->view->lid=$data[0]['letterid'];
		   $this->view->tid=$data[0]['tid'];
		   $this->view->classid=$data[0]['classid'];
	  }else{
		   $this->view->data=$data; //print_r($str);exit;
	  }
		   }else{
			   
				//查找给运维发消息的班级uid，班级id是唯一的
				$sql = "select DISTINCT(from_uid) as tid,classid from letter where isdelete=0 and to_role='admin' and from_role='teacher'";	
				//echo $sql;exit;
				$cids = $this->_dbAdapter->fetchAll($sql);
				//print_r($cids);echo '<br />';
				//获得该班级的最后一条私信
				foreach($cids as $cid){
					//如果运维是回复的最后一条，则该记录被忽略,只显示老师为最后一条的信息
					$sql = "select from_role as role from letter where classid=".$cid['classid']." and (to_role='teacher' and to_uid=".$cid['tid'].") or(from_role='teacher' and from_uid='".$cid['tid']."') order by addtime desc limit 1";
					$one = $this->_dbAdapter->fetchOne($sql);
					//print_r($one);echo '<hr />';
					if($one=='teacher'){
						$sql = "select letterid,from_uid as tid,addtime,content,classid from letter where classid=".$cid['classid']." and from_uid=".$cid['tid']." order by addtime desc limit 1";
						//echo $sql;echo '<br />';
						$row = $this->_dbAdapter->fetchRow($sql);	
						$res[] = $row;
					}elseif($one=='admin'){
						$sql = "select letterid,to_uid as tid,addtime,content,classid from letter where classid=".$cid['classid']." and to_uid=".$cid['tid']." order by addtime desc limit 1";
						//echo $sql;echo '<hr />';
						$row = $this->_dbAdapter->fetchRow($sql);	
						$res[] = $row;
					}
				}
				//print_r($res);exit;
				$num=count($res);
				for($i=0;$i<$num-1;$i++){
					for($j=$i+1;$j<$num;$j++){
						if($res[$j]['addtime']>$res[$i]['addtime']){
							$t=$res[$j];
							$res[$j]=$res[$i];
							$res[$i]=$t;
						}
					}
				}
				//print_r($res);echo '<br />';exit;
				foreach($res as $k=>$rs){
					   $teacher[$k]['lid'] = $rs['letterid'];
					   $teacher[$k]['tid'] = $rs['tid'];
					   $teacher[$k]['classid'] = $rs['classid'];
					   $teacher[$k]['addtime'] = MyClass_Common::getDateInfo($rs['addtime']);
					   $sql = "select groupid,groupname,schoolname,classname,teachername from teacher_class_duty_v where classid=".$rs['classid']." and teacherid='".$rs['tid']."'";
					   $row = $this->_dbAdapter->fetchRow($sql);
					   $teacher[$k]['groupid']  = $row['groupid'];
					   $teacher[$k]['groupname']  = $row['groupname'];
					   $teacher[$k]['schoolname'] = $row['schoolname'];
					   $teacher[$k]['classname']  = $row['classname'];
					   $teacher[$k]['teachername']  = $row['teachername'];
					   $teacher[$k]['content']    = mb_substr($rs['content'],0,15);
				}
				//print_r($teacher);echo '<br />';
				$num=count($teacher);//print_r($num);exit;
				for($i=0;$i<$num-1;$i++){
					for($j=$i+1;$j<$num;$j++){
						if($teacher[$j]['groupid']<$teacher[$i]['groupid']){
							$t=$teacher[$j];
							$teacher[$j]=$teacher[$i];
							$teacher[$i]=$t;
						}
					}
				}
				$this->view->teacher=$teacher; 
				//print_r($teacher);exit;
		   }
		     
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//发件
	public function sendAction(){
        try {
		   if ($this->isPost ()) {
			    $from_role = 'admin';		
                $from_uid  = $this->_user->id;
				$p = $this->_request->getPost();
				//print_r($p);exit;
				if(empty($p['toids'])){
				    throw new Exception ('请选择消息发送对象');
				}
				
				$toids = substr($p['toids'],0,strlen($p['toids'])-1);
				$ids = explode(',',$toids);							
				$to_role   = 'teacher';
				$content   = addslashes(trim($p['content']));
				$addtime   = time();
				$letter_type = !empty($p['content'])?'txt':'img';
				foreach($ids as $id){
					$sql='select teacherid,classid from teacher_class_duty_v where inactive=0 and teacherclassid='.$id;
					$teacherinfo=$this->_dbAdapter->fetchRow($sql);
					$teacherid=$teacherinfo['teacherid'];
					//print_r($teacherinfo);exit;
					$letter = array(
					   'from_role'=>$from_role,
					   'from_uid'=>$from_uid,
					   'to_role'=>$to_role,
					   'to_uid'=>$teacherinfo['teacherid'],
					   'letter_type'=>$letter_type,
					   'content'=>$content,
					   'addtime'=>$addtime,					
					   'classid'=>$teacherinfo['classid'],					
					);
					$this->_dbAdapter->Insert('letter',$letter);
					$id = $this->_dbAdapter->lastInsertId();
					$lids[] = $id;
					if(!$id){
						throw new Exception ( -4);
					}
					$res =1;
					
				    //push_message($type,$schoolid=0,$classid=0,$uid=0,$isstudent=1,$wantsenttime=0) 
				    $this->push_message('letter',0,0,$teacherid,0,0);
			    }				
				if(!empty($_FILES['pic']['tmp_name'])){//图片
                    $ext = explode('.', $_FILES['pic']['name']);
                    $imgname = $from_uid."_".time().'_'.$_FILES['pic']['size'];
                    $tmppath = APPLICATION_PATH.'/../tmp/letter/';
                    $smallfilename = $imgname.'.jpg.small.jpg';
                    $smallfileurl = $tmppath.$smallfilename;
                    $bigfilename = $imgname.'.jpg.big.jpg';					
                    $bigfileurl = $tmppath.$bigfilename;
					
                    $this->ThumbRatio($_FILES['pic']['tmp_name'],$smallfileurl,'227','128',1);
                    $this->ThumbRatio($_FILES['pic']['tmp_name'],$bigfileurl,'1136','640',1);
                    if(file_exists($smallfileurl)&&file_exists($bigfileurl)){
					   $res1 = Azure_Storage::defaultImg('letter', $smallfileurl, $imgname.'.jpg.small.jpg');
					   $res2 = Azure_Storage::defaultImg('letter', $bigfileurl, $imgname.'.jpg');
					   $uptime = time();
					   if($res1&&$res2){
					        foreach($lids as $id){
							   $data = array(
							      'letterid'=>$id,
								  'filename'=>$imgname,
								  'fext'=>'jpg',
								  'uploadtime' =>$uptime,
							   );
							   $this->_dbAdapter->Insert('letter_files',$data);
							   $id = $this->_dbAdapter->lastInsertId();
							   if(!$id){
								  throw new Exception ('letter_file添加图片错误');
							   }
							  
							}
					   }
					   $res =1;
					}
				}
				
				
				
                if( $res )
                        $this->feedback ( '增加成功', '注意', '/'.$this->controller, 'warning' );
                else 
                        throw new Exception ( '增加失败 ！' );
		   }else{
		     $result = $this->_dbAdapter->fetchAll("select groupid,groupname from groups");				
		     $this->view->result=$result;   
		   }           
	    } catch ( Exception $e ) {
		   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
	    }
    }
	//回复
	public function replyAction(){
	   try {
	      if($this->isPost()){
				$from_role = 'admin';		
				$from_uid  = $this->_user->id;
				$p = $this->_request->getPost();
			  //print_r($p);echo '<br />';exit;
				
				$lid = $p['lid'];
				$tid = $p['tid'];
				$classid = $p['classid'];
				$row = $this->_dbAdapter->fetchRow("select from_role,from_uid,to_uid,classid from letter where letterid='".$lid."'");
				if($row['from_role']=='admin'){
					$to_uid    = $row['to_uid'];
				}else{
					$to_uid    = $row['from_uid'];
				}
				$to_role   = 'teacher';
				$content   = addslashes(trim($p['content']));
				$addtime   = time();
				$letter_type = !empty($p['content'])?'txt':'img';
				$letter = array(
				   'from_role'=>$from_role,
				   'from_uid'=>$from_uid,
				   'to_role'=>$to_role,
				   'to_uid'=>$to_uid,
				   'letter_type'=>$letter_type,
				   'content'=>$content,
				   'addtime'=>$addtime,
				   'classid'=>$classid,					
				);
				//print_r($letter);exit;
				$this->_dbAdapter->Insert('letter',$letter);
				$letterlastid = $this->_dbAdapter->lastInsertId();
				
				if(!$letterlastid ){
					throw new Exception ('letter表录入失败');
				}
				$res =1;
				
				if(!empty($_FILES['pic']['tmp_name'])){//图片
				
                    $ext = explode('.', $_FILES['pic']['name']);
                    $imgname = $from_uid."_".time().'_'.$_FILES['pic']['size'];
                    $tmppath = APPLICATION_PATH.'/../tmp/letter/';
                    $smallfilename = $imgname.'.jpg.small.jpg';
                    $smallfileurl = $tmppath.$smallfilename;
                    $bigfilename = $imgname.'.jpg.big.jpg';
					
                    $bigfileurl = $tmppath.$bigfilename;
					
                    $this->ThumbRatio($_FILES['pic']['tmp_name'],$smallfileurl,'227','128',1);
                    $this->ThumbRatio($_FILES['pic']['tmp_name'],$bigfileurl,'1136','640',1);
					
                    if(file_exists($smallfileurl)&&file_exists($bigfileurl)){
					   $res1 = Azure_Storage::defaultImg('letter', $smallfileurl, $imgname.'.jpg.small.jpg');
					   $res2 = Azure_Storage::defaultImg('letter', $bigfileurl, $imgname.'.jpg');
					   $uptime = time();
					   if($res1&&$res2){
					        $data = array(
							      'letterid'=>$letterlastid,
								  'filename'=>$imgname,
								  'fext'=>'jpg',
								  'uploadtime' =>$uptime,
							   );
							   $this->_dbAdapter->Insert('letter_files',$data);
							   $id = $this->_dbAdapter->lastInsertId();								
							   if(!$id){
								  throw new Exception ('letter_file添加图片错误');
							   }
					   }
					   $res =1;
					}
				}
				$this->push_message('letter',0,0,$to_uid ,0,0);
				//更新已回复
				  // $sql='update letter set reply_letterid="'.$letterlastid.'" where letterid='.$lid;
				  // $result = $this->_dbAdapter->query($sql);
				 
				 //http://127.0.0.1:8005/letter/history/letterid/494/group_id/1/content/%E
				 if( $res ){
				 	if($p['tid']){
						$this->feedback ( '回复成功', '注意', '/'.$this->controller.'/reply/tid/'.$p['tid'].'/classid/'.$p['classid'], 'warning' );
					}elseif($p['history']){
						$this->feedback ( '回复成功', '注意', '/'.$this->controller.'/history', 'warning' );
					}
				 }else{ 
					throw new Exception ( '回复失败 ！' );
				 }
		   }else{
			   if(!$this->_request->getParam ( 'tid' )){
				   throw new Exception ( '没有传递GET参数 ！' );	
			   }
               $tid = $this->_request->getParam ('tid');
               $classid = $this->_request->getParam ('classid');
               $addtime = trim($this->_request->getParam ('addtime'));
			   $addtime=strtotime($addtime);
			   //print_r($addtime);exit;
		       $sql = "select letterid,from_role,content,addtime,letter_type,classid from letter where classid=".$classid." and  from_role='teacher' and from_uid=".$tid." or ( to_role='teacher' and to_uid=".$tid.") order by addtime desc limit 5" ;
		       $result = $this->_dbAdapter->fetchAll($sql);
			   $result=array_reverse($result);
			   //print_r($result);exit;
			   foreach($result as $k=>$ar){
					$role[] =  $ar['from_role'];
					$data[$k]['role'] = $ar['from_role'];
					$letterid=$ar['letterid'];
					
					if($ar['from_role']=='admin'){
						$data[$k]['uname'] == '运维';
					}else{
						$r = $this->_dbAdapter->fetchRow("select groupname,groupid,schoolname,classname,teachername from teacher_class_duty_v where classid=".$classid." and teacherid='".$tid."'");				
						$data[$k]['detail']  = $r['groupname'].">".$r['schoolname'].">".$r['teachername'];
						$data[$k]['uname']  = $r['teachername'];
						$groupid  = $r['groupid'];
					}
					
					if($ar['letter_type']=='img'){			   
						$sql = "select concat('http://',cloudhost,cloudpath,filename,'.',fext,'.small.jpg') as imgurl,concat('http://',cloudhost,cloudpath,filename,'.',fext) as bigurl from letter_files where letterid='".$ar['letterid']."'";
						$r = $this->_dbAdapter->fetchRow($sql);
						$data[$k]['content'] = "<a href='#bigImg".$ar['letterid']."' role='button' class='btn' data-toggle='modal'><img src='".$r['imgurl']."' alt='没有找到云上的图片'></a>
                                            <div id='bigImg".$ar['letterid']."' class='modal hide fade' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
  <div class='modal-header'>
    <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
    <h3 id='myModalLabel'>Modal header</h3>
  </div>
  <div class='modal-body'>
    <img src='".$r['bigurl']."' alt='没有找到云上的大图片'>
  </div>
</div>";
					}else{
						//$data[$k]['content'] = $ar['content'];
						$data[$k]['content']=str_replace(' ','&nbsp;',str_replace("\r\n",'<br>',$ar['content']));
					}
					$data[$k]['addtime'] = MyClass_Common::getDateInfo($ar['addtime']);
					//$data[$k]['content']=str_replace(' ','&nbsp;',str_replace("\n",'<br>',$ar['content']));
			   }			   
			}
			//print_r($data);exit;
			$this->view->lid = $result[count($result)-1]['letterid'];
			$this->view->data = $data;
			$this->view->tid = $tid;
			$this->view->classid = $classid;
			$this->view->groupid = $groupid;
			$this->view->content = $content;
			//print_r($content);exit;
			$this->view->letterid = $letterid;
			
			for($i=0;$i<count($data);$i++){
				if($data[$i]['detail']){
					$this->view->who = $data[$i];
					break;
				}
			}
			
		   //更新reply_letterid
	    } catch ( Exception $e ){
		   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
	    }
	}
	
/*	//查看
	public function seeAction(){
	   try{	       
	        $cid = $this->_request->getParam ('cid');
		   $sql = "select letterid,from_role,content,addtime,letter_type from letter where from_role='teacher' and from_uid=".$cid." or (to_role='teacher' and to_uid=".$cid.") order by addtime asc limit 0,20" ;
		   $result = $this->_dbAdapter->fetchAll($sql);
		    foreach($result as $k=>$ar){
			    $role[] =  $ar['from_role'];
				$data[$k]['role'] = $ar['from_role'];
		        if($ar['from_role']=='admin'){
				    $data[$k]['uname'] == '运维';
				}else{
					$r = $this->_dbAdapter->fetchRow("select g.groupname,c.schoolname,c.classname from class c join groups g where c.groupid = g.groupid and c.uid='".$cid."'");				
					$data[$k]['detail']  = $r['groupname'].">".$r['schoolname'];
					$data[$k]['uname']  = $r['classname'];
				}
		        if($ar['letter_type']=='img'){			   
					$sql = "select concat('http://',cloudhost,cloudpath,filename,'.',fext,'.small.jpg') as imgurl from letter_files where letterid='".$ar['letterid']."'";
					$r = $this->_dbAdapter->fetchRow($sql);
					$data[$k]['content'] =  "<a href='#bigImg".$r['letterid']."' role='button' class='btn' data-toggle='modal'><img src='".$r['imgurl']."' alt='没有找到云上的图片'></a>
                                            <div id='bigImg".$ar['letterid']."' class='modal hide fade' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
  <div class='modal-header'>
    <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
    <h3 id='myModalLabel'>Modal header</h3>
  </div>
  <div class='modal-body'>
    <img src='".$r['bigurl']."' alt='没有找到云上的大图片'>
  </div>
</div>";
				}else{
					$data[$k]['content'] = $ar['content'];
				}
				$data[$k]['addtime'] = date('Y-m-d H:i:s',$ar['addtime']);
		   }
		   foreach($data as $da){
		       $str .="<div>";			  			   
			   $str .= $da['role']=="teacher"?$da['uname']."&nbsp&nbsp&nbsp".$da['detail'].":":'运维';	
               $str .="<small>[";
			   $str .= $da['addtime'];	
               $str .="]</small>";
			   $str .="</div>";
			   $str .="<div>";	
			   $str .="&nbsp&nbsp&nbsp&nbsp".$da['content'];
			   $str .="</div><br />";
		   }
		   $this->view->table  = $str;
	   } catch ( Exception $e ){
		   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
	   }
	}
*/	//删除
	public function deleteAction(){
	   try {
		   $cid = $this->_request->getParam ('cid');
		   if(!$cid ){		       
			   throw new Exception ( '没有传递GET参数 ！' );	
		   }
		   $sql = "select letterid from letter where from_uid='".$cid."'  or to_uid='".$cid."'";
		   $lidarr = $this->_dbAdapter->fetchAll($sql);	
		   foreach($lidarr as $li){
		      $arr[] = $li['letterid'];
		   }
		   $lids = implode(',',$arr);
		   $sql = "update letter set isdelete=1 where letterid in(".$lids.")";
		   $result = $this->_dbAdapter->query($sql);				 
		   if( $result )
			  $this->feedback ( '删除成功', '注意', '/'.$this->controller, 'warning' );
		   else 
			  throw new Exception ( '删除失败 ！' );		   
	   }catch ( Exception $e ) {
		   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
	   }	   
	}
	//清空回收站
	public function clearallAction(){
	   try {		   
		   $sql = "delete from  letter  where isdelete=1";
		   $result = $this->_dbAdapter->query($sql);				 
		   if( $result )
			  $this->feedback ( '回收站已清空', '注意', '/'.$this->controller, 'warning' );
		   else 
			  throw new Exception ( '清空失败 ！' );		   
	   }catch ( Exception $e ) {
		   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
	   }	   
	}
	//彻底删除
	public function clearAction(){
	   try {
		    $cid = $this->_request->getParam ('cid');
		   if(!$cid ){		       
			   throw new Exception ( '没有传递GET参数 ！' );	
		   }
		   $sql = "select letterid from letter where from_uid='".$cid."'  or to_uid='".$cid."'";
		   $lidarr = $this->_dbAdapter->fetchAll($sql);	
		   foreach($lidarr as $li){
		      $arr[] = $li['letterid'];
		   }
		   $lids = implode(',',$arr);
		   $sql = "delete from  letter  where letterid in(".$lids.")";
		   $result = $this->_dbAdapter->query($sql);				 
		   if( $result )
			  $this->feedback ( '已彻底删除所有数据', '注意', '/'.$this->controller, 'warning' );
		   else 
			  throw new Exception ( '删除失败 ！' );		   
	   } catch ( Exception $e ) {
		   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
	   }	   
	}
	
    //回收站
	public function recycleAction(){
        try {		    
		    $count = 15;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
			if (! $curpage) $curpage = 1;
			$offset = ($curpage - 1) * $count;	
			//查找给运维发消息的班级uid，班级id是唯一的
            $sql = "select DISTINCT(to_uid) as cid from letter where isdelete=1 and from_role='admin'";	
			$cid1 = $this->_dbAdapter->fetchAll($sql);
			$sql = "select DISTINCT(from_uid) as cid from letter where isdelete=1 and to_role='admin'";	
			$cid2 = $this->_dbAdapter->fetchAll($sql);
			foreach($cid1 as $cid){
			   $cids[] = $cid['cid'];
			}
			foreach($cid2 as $cid){
			   $cids[] = $cid['cid'];
			}
			$cids = array_unique($cids);
			foreach($cids as $cid){
			    $sql = "select SQL_CALC_FOUND_ROWS letterid,from_uid as cid,addtime,content from letter where from_uid=".$cid." or to_uid=".$cid." order by addtime desc limit 1";
				$row = $this->_dbAdapter->fetchRow($sql);	
				$result[] = $row;			
			}
			
			$param ['file'] = '/' . $this->controller . '/' . $this->action.'/aa';
			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
			$param ['perpagenum'] = $count;    // 每页显示的数目
			$param ['disnum'] = 11;            // 取单数显示，当前页停在中间
			$param ['curpage'] = $curpage;     // 当前页码
			$this->view->allnum= $param ['totalnum'];
			$page = new MyClass_Page ($param );		
			$this->view->page= $page->getNumPage ();
			foreach($result as $k=>$rs){
				   $data[$k]['lid'] = $rs['letterid'];
				   $data[$k]['cid'] = $rs['cid'];
				   $data[$k]['addtime'] = date('Y-m-d H:i:s',$rs['addtime']);
				   $sql = "select g.groupname,c.schoolname,c.classname from class c  join groups g where c.groupid=g.groupid and c.uid=".$rs['cid'];
				   $row = $this->_dbAdapter->fetchRow($sql);
				   $data[$k]['groupname']  = $row['groupname'];
				   $data[$k]['schoolname'] = $row['schoolname'];
				   $data[$k]['classname']  = $row['classname'];
				   $data[$k]['content']    = mb_substr($rs['content'],0,15);
			}			
			$this->view->tnum=count($data);
			$this->view->data=$data; 
			//print_r($data);exit();
		   // $result = $this->_dbAdapter->fetchAll("select groupid,groupname from groups");				
		   // $this->view->result=$result; 
			
		} catch ( Exception $e ){
		   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
    }
    //恢复
	public function gobackAction(){
	   try {
		   $cid = $this->_request->getParam ('cid');
		   if(!$cid ){		       
			   throw new Exception ( '没有传递GET参数 ！' );	
		   }
		   $sql = "select letterid from letter where from_uid='".$cid."'  or to_uid='".$cid."'";
		   $lidarr = $this->_dbAdapter->fetchAll($sql);	
		   foreach($lidarr as $li){
		      $arr[] = $li['letterid'];
		   }
		   $lids = implode(',',$arr);
		   $sql = "update letter set isdelete=0 where letterid in(".$lids.")";
		   $result = $this->_dbAdapter->query($sql);				 
		   if( $result )
			  $this->feedback ( '恢复成功', '注意', '/'.$this->controller, 'warning' );
		   else 
			  throw new Exception ( '恢复失败 ！' );		   
	   }catch ( Exception $e ) {
		   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
	   }	
	}
	//联动学校
    public function getschAction(){
		try {                   
		   $gid = $this->_request->getParam ( 'groupid' );
			   $result = $this->_dbAdapter->fetchAll("select distinct(schoolid),schoolname from class where schoolname<>'' and groupid=".$gid." order by schoolid asc");
			   foreach($result as $rs){
			      $ids = array('gid'=>$gid,'sid'=>$rs['schoolid']);
				  $ids = Zend_Json::encode($ids);
				  //$ul .= "<li id='sch".$rs['schoolid']."' class='sch'><span class='file' onclick='getcla(".$ids.")'>".$rs['schoolname']."</span></li>";
				  $ul .="<li onclick='getcla(".$ids.")'>".$rs['schoolname']."</li>
				 <ul class='three' id='three_".$rs['schoolid']."'></ul>";
			   }
			   echo !empty($ul)?$ul:''; exit();
			} catch ( Exception $e ){
							$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
			}
	}
    //联动班级
	public function getclaAction(){
		try {                   
		   $gid = $this->_request->getParam ('gid');
		   $sid = $this->_request->getParam ('sid');
		   //print_r($gid);echo '<br />';print_r($sid);exit;
		   $result = $this->_dbAdapter->fetchAll("select distinct(classid),classname from class where classname<>'' and schoolid=".$sid." and groupid=".$gid." and isdel=0 order by classid asc");
		   //print_r($result);exit;
		   $ul = '<ul>';
		   $arr = array();
		   foreach($result as $rs){
			  $ids = array('gid'=>$gid,'cid'=>$rs['classid']);
			  $ids = Zend_Json::encode($ids);
			  //$ul .= "<li class='cla' id='cla".$rs['uid']."' ><span class='file' onclick='getList(".$rs['uid'].")'>".$rs['classname']."</span></li>";
			  $ul .="<li onclick='gettea(".$ids.")'>".$rs['classname']."</li>
			  <ul class='four' id='four_".$rs['classid']."'></ul>";
		   }
			$ul .= '</ul>';			   
		   echo $ul=!empty($ul)?$ul:'';exit();
		} catch ( Exception $e ) {
						$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
    }
    //联动班级教师
	public function getteaAction(){
		try {                   
		   $gid = $this->_request->getParam ('gid');
		   $cid = $this->_request->getParam ('cid');
		   //print_r($gid);echo '<br />';print_r($cid);exit;
		   $result = $this->_dbAdapter->fetchAll("select teacherclassid,teacherid,teachername,classname from teacher_class_duty_v where inactive=0 and classid=".$cid." and groupid=".$gid." order by teacherclassid asc");
		   $ul = '<ul>';
		   $arr = array();
		   foreach($result as $rs){
			  $ul .= "<li class='tea' id='tea".$rs['teacherclassid']."' ><span class='file' onclick='getList(".$rs['teacherclassid'].")'>".$rs['teachername']."</span></li>";
		   }
			$ul .= '</ul>';			   
		   echo $ul=!empty($ul)?$ul:'';exit();
		} catch ( Exception $e ) {
						$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
    }
	public function getsendteaAction(){
		try {                   
		   $gid = $this->_request->getParam ('gid');
		   $cid = $this->_request->getParam ('cid');
		   $result = $this->_dbAdapter->fetchAll("select teacherclassid,teacherid,teachername,classname from teacher_class_duty_v where inactive=0  and classid=".$cid." and groupid=".$gid." order by teacherclassid asc");
		   $ul = '<ul>';
		   $arr = array();
		  
		   foreach($result as $rs){
		       $arr = array('teacherclassid'=>$rs['teacherclassid'],'teachername'=>$rs['teachername']);
		       $arr = Zend_Json::encode($arr);
			  $ul .= "<li class='tea' id='tea".$rs['teacherclassid']."' ><span class='file' onclick='addtouser(".$arr.")'>".$rs['teachername']."</span></li>";
		   }
			$ul .= '</ul>';			   
		   echo $ul=!empty($ul)?$ul:'';exit();
		} catch ( Exception $e ) {
						$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
    }
/*	//获得该班级的所有通话记录
	public function getlistAction(){
	    try { 
		   $cid = $this->_request->getParam ('cid');
		   $sql = "select letterid,from_role,content,addtime,letter_type from letter where isdelete=0 and (from_role='teacher' and from_uid=".$cid." or (to_role='teacher' and to_uid=".$cid.") ) order by addtime asc " ;
		   //echo $sql;exit;
		   $result = $this->_dbAdapter->fetchAll($sql);
		    foreach($result as $k=>$ar){
			    $role[] =  $ar['from_role'];
				$data[$k]['role'] = $ar['from_role'];
		        if($ar['from_role']=='admin'){
				    $data[$k]['uname'] == '运维';
				}else{
					$r = $this->_dbAdapter->fetchRow("select g.groupname,c.schoolname,c.classname from class c join groups g where c.groupid = g.groupid and c.uid='".$cid."'");				
					$data[$k]['detail']  = $r['groupname'].">".$r['schoolname'];
					$data[$k]['uname']  = $r['classname'];
				}
		        if($ar['letter_type']=='img'){			   
					$sql = "select concat('http://',cloudhost,cloudpath,filename,'.',fext,'.small.jpg') as imgurl,concat('http://',cloudhost,cloudpath,filename,'.',fext) as bigurl from letter_files where letterid='".$ar['letterid']."'";
					$r = $this->_dbAdapter->fetchRow($sql);
					$data[$k]['content'] = "<a href='#bigImg".$ar['letterid']."' role='button' class='btn' data-toggle='modal'><img src='".$r['imgurl']."' alt='没有找到云上的图片'></a>
                                            <div id='bigImg".$ar['letterid']."' class='modal hide fade' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
  <div class='modal-header'>
    <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
    <h3 id='myModalLabel'>Modal header</h3>
  </div>
  <div class='modal-body'>
    <img src='".$r['bigurl']."' alt='没有找到云上的大图片'>
  </div>
</div>";
				}else{
					$data[$k]['content'] = $ar['content'];
				}
				$data[$k]['addtime'] = date('Y-m-d H:i:s',$ar['addtime']);
		   }
		  
		   foreach($data as $da){
			   if($da['role']=='teacher'){
		       	    $str .="<div class='from'>";			  			   
			   }else{
		       	    $str .="<div class='to'>";			  			   
			   }
			   			  			   
			   $str .= $da['role']=="teacher"?$da['uname']."&nbsp&nbsp&nbsp".$da['detail'].":":'运维';	
               $str .= $da['addtime'];		   
			   $str .="</div>";
			   
			   if($da['role']=='teacher'){
					$str .="<p class='from1 alert alert-error'>";			  			   
			   }else{
					$str .="<p class='to1 alert alert-success'>";			  			   
			   }
			   $str .="&nbsp;".$da['content'];
			   $str .="</p>";
		   }
		    $start ="<div><a href='/letter/delete/cid/".$cid."'>删除记录</a></div><br />";	
		   echo !empty($str)?$start.$str:'';exit();
	    } catch ( Exception $e ) {
						$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
*/	
	
	public function push_message($type,$schoolid=0,$classid=0,$uid=0,$isstudent=1,$wantsenttime=0) {
		//$this->buildDbAdapter('centraldb');
		$timenow=time();
		if(!$wantsenttime)
			$wantsenttime=$timenow;
		if($isstudent){
		}else{
			if($type=='letter'){
				if(!$uid)
					return -100;
				
				$content="有一条新消息了。Have a new message.";
				$this->_dbAdapter->query('insert push_class_content (`uid`,`token`,`contenttype`,`content`,`addtime`,`wantsenttime`) select uid,token,"'.$type.'","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_class_token where uid='.$uid);
				$this->log('insert push_class_content (`uid`,`token`,`contenttype`,`content`,`addtime`,`wantsenttime`) select uid,token,"'.$type.'","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_class_token where uid='.$uid);
			}//end letter		
		}
	}
	

	public function __call($method, $args){
		if ('Action' == substr ( $method, - 6 )) {
			$url = '/' . $this->controller . '/index';
			return $this->_redirect ( $url );
		}
		throw new Exception ( 'Invalid method' );
	}
}
?>
